import socket,select,struct,time
from helpFunc import *
import random

def makeMsg():
    ll = random.randint(100,10000)
    return struct.pack('I',ll)+b'a'*(ll-4)

class testconn():
    def __init__(self,dataPort,numPort):
        add = ('127.0.0.1',dataPort)
        sockData = socket.socket()
        while True:
            try:
                sockData.connect(add)
                break
            except:
                time.sleep(0.2)
        print ('conn1')      
        add = ('127.0.0.1',numPort)
        sockNum = socket.socket()
        while True:
            try:
                sockNum.connect(add)
                break
            except:
                time.sleep(0.2)
        print ('conn2')  
        recBuf = b''
        cacheSize = 1024*1024
        msgBuf = b''
        staGot  = staMsgGot = 0
        staTime = time.monotonic()
        while True:
            r,w,e = select.select([sockData,sockNum],[],[],0.1)
            if sockNum in r:
                recBuf += sockNum.recv(tcpReadLen)
                while len(recBuf)>=4:
                    cacheSize += struct.unpack('I',recBuf[:4])[0]
                    recBuf = recBuf[4:]
            if sockData in r:
                dd = sockData.recv(tcpReadLen)
                staGot += len(dd)
                msgBuf += dd
                msgBuf,l = dealData(msgBuf)
                if l:
                    staMsgGot += len(l)
            while cacheSize>0:
                msg = makeMsg()
                cacheSize -= len(msg)
                sockData.sendall(msg)
            if time.monotonic()-staTime>1:
                staTime = time.monotonic()
                #print (staTime,staGot,staMsgGot)
                staGot = staMsgGot=0